/**
 * <pre>
   Copyright 2016 aaron.sd

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 * </pre>
 * 
 * @author aaronwong.sd@foxmail.com
 * @version 下午12:07:28
 */
package com.iwechat.mp.service.task;

import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.iwechat.config.CommConst;
import com.iwechat.mp.service.TemplateMessageHandler;
import com.iwechat.mybatis.generator.dao.TmpsMessageRespMapper;
import com.iwechat.mybatis.generator.model.TmpsMessageResp;

/**
 * 模板消息处理器
 * 
 * @author aaronwong.sd@foxmail.com
 */
@Service("tmhandler")
public class TemplateMessageHandlerImpl implements TemplateMessageHandler {
    private static final long                             initialDelay = 1 * 1000;
    private static final long                             fixedDelay   = 60 * 1000;
    private static final int                              batchCount   = 1024;

    public static final ConcurrentLinkedQueue<JSONObject> RESP_POOL    = new ConcurrentLinkedQueue<JSONObject>();

    @Autowired
    TmpsMessageRespMapper                                 respMapper;

    /*
     * (non-Javadoc)
     * 
     * @see com.iwechat.mp.service.TemplateMessageHandler#saveResponse()
     */
    @Override
    @Scheduled(initialDelay = initialDelay, fixedDelay = fixedDelay)
    public void saveResponse() {
        int size = RESP_POOL.size();
        if (size > 0) {
            if (size > batchCount) {
                size = batchCount;
            }
            List<TmpsMessageResp> list = new LinkedList<TmpsMessageResp>();
            for (int i = 0; i < size; i++) {
                // 获取队列最靠前的一个
                JSONObject json = RESP_POOL.poll();
                TmpsMessageResp resp = new TmpsMessageResp();
                resp.setSeqnb(json.getLong(CommConst.SEQNB));
                resp.setErrcode(json.getIntValue("errcode"));
                resp.setErrmsg(json.getString("errmsg"));
                Long msgid = json.getLong("msgid");
                if (msgid == null) {
                    msgid = -1L;
                }
                resp.setMsgid(msgid.longValue());
                list.add(resp);
            }
            respMapper.insertBatch(list);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.iwechat.mp.service.TemplateMessageHandler#saveReport()
     */
    @Override
    @Scheduled(initialDelay = initialDelay, fixedDelay = fixedDelay)
    public void saveReport() {
        // TODO Auto-generated method stub
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.iwechat.mp.service.TemplateMessageHandler#addResponse(com.alibaba.fastjson.JSONObject)
     */
    @Override
    public void addResponse(JSONObject resp) {
        if (resp != null) {
            RESP_POOL.offer(resp);
        }
    }

    @Override
    public String monitorResp() {
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(2);
        StringBuffer buffer = new StringBuffer(128);
        buffer.append("RESP_POOL");
        buffer.append("\n");
        buffer.append("### size : " + RESP_POOL.size());
        return buffer.toString();
    }

}
